﻿using System.Collections.Generic;

namespace CxExtension
{
	public class RefCounter<T>: RefCounter<T,T>
	{

	}
	public class RefCounter<K,V>
	{
		public Dictionary<K, RefCountInfo<K, V>> CountMap { get; } = new Dictionary<K, RefCountInfo<K, V>>();

		public HashSet<K> ChangedSet { get; } = new HashSet<K>();

		public void ClearChangeSet()
		{
			ChangedSet.Clear();
		}
		public void AddRef(K key, V refValue)
		{
			var info = CountMap.GetOrNewAddF(key, NewRefCountInfo);
			info.AddRef(refValue);
		}
		public bool RemoveRef(K key, V refValue)
		{
			if (CountMap.TryGetValue(key, out var info))
			{
				ChangedSet.Add(key);
				return info.RemoveRef(refValue);
			}
			else
			{
				return false;
			}
		}

		public int GetRefCount(K key)
		{
			if (CountMap.TryGetValue(key, out var info))
			{
				return info.Count;
			}
			else
			{
				return -1;
			}
		}
		private RefCountInfo<K, V> NewRefCountInfo(K it)
		{
			var info = new RefCountInfo<K, V> {Key = it};
			return info;
		}
	}
}